using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using ASMdll;
using System.Diagnostics;
using System.Threading;

namespace ASM
{
	public partial class Form1 : Form
	{
		private string path = null;

		TranslationResult tr = null;

		public Form1()
		{
			InitializeComponent();
		}

		private void newToolStripMenuItem_Click(object sender, EventArgs e)
		{
			if (path != null)
			{
				DialogResult dr = MessageBox.Show("Save changes in current file?", "", MessageBoxButtons.YesNoCancel);
				if (dr == DialogResult.Yes)
					Save();
				if (dr == DialogResult.Cancel)
					return;
				Close();
			}
			saveFileDialog1.Filter = "ASM files (*.asm) |*.asm";
			if (saveFileDialog1.ShowDialog() == DialogResult.OK)
			{
				path = saveFileDialog1.FileName;
				StreamWriter sw = new StreamWriter(path);
				sw.Close();
				richTextBox1.Visible = true;
				saveToolStripMenuItem.Enabled = true;
				compileToolStripMenuItem.Enabled = true;
				runToolStripMenuItem.Enabled = true;
			}
		}

		private void openToolStripMenuItem_Click(object sender, EventArgs e)
		{
			if (path != null)
			{
				DialogResult dr = MessageBox.Show("Save changes in current file?", "", MessageBoxButtons.YesNoCancel);
				if (dr == DialogResult.Yes)
					Save();
				if (dr == DialogResult.Cancel)
					return;
				Close();
			}
			openFileDialog1.Filter = "ASM files (*.asm) |*.asm";
			if (openFileDialog1.ShowDialog() == DialogResult.OK)
			{
				path = openFileDialog1.FileName;
				StreamReader sr = new StreamReader(path);
				richTextBox1.Text = sr.ReadToEnd();
				sr.Close();
				richTextBox1.Visible = true;
				saveToolStripMenuItem.Enabled = true;
				compileToolStripMenuItem.Enabled = true;
				runToolStripMenuItem.Enabled = true;
			}
		}

		private void Save()
		{
			StreamWriter sw = new StreamWriter(path);
			sw.Write(richTextBox1.Text);
			sw.Close();
		}

		private void Close()
		{
			path = null;
			saveToolStripMenuItem.Enabled = false;
			compileToolStripMenuItem.Enabled = false;
			runToolStripMenuItem.Enabled = false;
			richTextBox1.Visible = false;
			richTextBox1.Text = "";
			dataGridView1.Rows.Clear();
		}

		private void saveToolStripMenuItem_Click(object sender, EventArgs e)
		{
			Save();
		}

		private void exitToolStripMenuItem_Click(object sender, EventArgs e)
		{
			Application.Exit();
		}

		private void compileToolStripMenuItem_Click(object sender, EventArgs e)
		{
			tr = Translator.Translate(richTextBox1.Text);

			symTabToolStripMenuItem.Enabled = false;

			dataGridView1.Rows.Clear();

			if (tr.ErrorReports.Count > 0)
			{
				foreach (KeyValuePair<int, string> k in tr.ErrorReports)
					dataGridView1.Rows.Add(k.Key, k.Value);
				return;
			}

			symTabToolStripMenuItem.Enabled = true;
			dataGridView1.Rows.Add("", "Compilation successful!");
		}

		private void runToolStripMenuItem_Click(object sender, EventArgs e)
		{
			tr = Translator.Translate(richTextBox1.Text);

			symTabToolStripMenuItem.Enabled = false;

			dataGridView1.Rows.Clear();

			if (tr.ErrorReports.Count > 0)
			{
				foreach (KeyValuePair<int, string> k in tr.ErrorReports)
					dataGridView1.Rows.Add(k.Key, k.Value);
				return;
			}

			symTabToolStripMenuItem.Enabled = true;

			dataGridView1.Rows.Add("", "Compilation successful!");

			try
			{
				string path1 = path.Substring(0, path.Length - 3) + "com";
				FileStream fs = new FileStream(path1, FileMode.Create, FileAccess.Write);
				BinaryWriter bw = new BinaryWriter(fs);
				for (int i = 256; i < tr.Code.Length; ++i)
					bw.Write(tr.Code[i]);
				bw.Close();

				dataGridView1.Rows.Add("", "Creating com-file successful!");

				string path2 = path.Substring(0, path.Length - 3) + "bat";
				FileStream fs1 = new FileStream(path2, FileMode.Create, FileAccess.Write);
				StreamWriter sw = new StreamWriter(fs1);
				sw.WriteLine("ECHO OFF");
				sw.WriteLine("CLS");
                sw.WriteLine("\"" + path1 + "\"");
				sw.WriteLine("PAUSE");
				sw.WriteLine("EXIT");
				sw.Close();

				dataGridView1.Rows.Add("", "Creating bat-file successful!");

                bool runed = false;
                for (int i = 0; i < 100; ++i)
                {
                    Thread.Sleep(1000);
                    runed = true;
                    try
                    {
                        Process.Start(path2);
                    }
                    catch
                    {
                        runed = false;
                    }
                    if (runed)
                        break;
                }
                if (!runed)
                    throw new Exception("Can not run com-file!");

				dataGridView1.Rows.Add("", "Running com-file successful!");
			}
			catch (Exception e_)
			{
				dataGridView1.Rows.Add("", "Error while creating executable file! " + e_.Message);
			}
		}

		private void Form1_FormClosing(object sender, FormClosingEventArgs e)
		{
			if (path != null)
			{
				DialogResult dr = MessageBox.Show("Save changes in current file?", "", MessageBoxButtons.YesNoCancel);
				if (dr == DialogResult.Yes)
					Save();
				if (dr == DialogResult.Cancel)
				{
					e.Cancel = true;
					return;
				}
				Close();
			}
		}

		private void symTabToolStripMenuItem_Click(object sender, EventArgs e)
		{
			new SymTab_(tr).Show();
		}

		private void richTextBox1_Enter(object sender, EventArgs e)
		{
			toolStripStatusLabel1.Text = "Line " + richTextBox1.SelectionStart;
		}

		private void richTextBox1_Leave(object sender, EventArgs e)
		{
			toolStripStatusLabel1.Text = "";	
		}

		private void richTextBox1_SelectionChanged(object sender, EventArgs e)
		{
			toolStripStatusLabel1.Text = "Line " + (richTextBox1.GetLineFromCharIndex(richTextBox1.SelectionStart) + 1).ToString();
		}
	}
}